import fetch from 'dva/fetch';
import { notification } from 'antd';

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  notification.error({
    message: `请求错误 ${response.status}: ${response.url}`,
    description: response.statusText,
  });

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

function errorHandle(error) {
  if (error.code) {
    notification.error({
      message: error.name,
      description: error.message,
    });
  }
  if ('stack' in error && 'message' in error) {
    notification.error({
      message: '请求错误',
      description: error.message,
    });
  }
  return error;
}

export const SERVER_API_HOST = '/api/v1';

// default header
// 1. auth header
// 2. tobe added
const getDefaultOptions = () => {
  const token = localStorage.getItem('token');
  return {
    Authorization: `Bearer ${token || ''}`,
  };
};

// add content-type header
const genJsonMimeHeaders = (options) => {
  return {
    Accept: 'application/json',
    'Content-Type': 'application/json; charset=utf-8',
    ...options.headers,
  };
};
/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  const defaultOptions = getDefaultOptions();
  const newOptions = { ...defaultOptions, ...options };
  const curMethod = newOptions.method && newOptions.method.toUpperCase();

  if (curMethod === 'POST' || curMethod === 'PUT') {
    newOptions.headers = genJsonMimeHeaders(options);
    newOptions.body = JSON.stringify(newOptions.body);
  }

  return fetch(url, newOptions)
    .then(checkStatus)
    .then(response => response.json())
    .catch(errorHandle);
}

export const postReq = request;
export const putReq = request;

export function deleteReq(url, options) {
  const defaultOptions = getDefaultOptions();
  const newOptions = { ...defaultOptions, ...options };

  if (newOptions.method.toUpperCase() !== 'DELETE') {
    console.error('unexpected method in delete request', newOptions.method);
    return;
  }

  newOptions.headers = genJsonMimeHeaders(options);
  newOptions.body = JSON.stringify(newOptions.body);

  return fetch(url, newOptions)
    .then(checkStatus)
    .then(response => response) // no response body, use raw response
    .catch(errorHandle);
}
